<?php

namespace app\services;

use app\lib\exception\ParamException;
use app\lib\exception\ServiceException;
use app\model\Airlines;
use app\model\Airports;
use app\model\FlightAvho;
use app\model\SystemConfig;
use app\utils\CharacterUtils;
use app\utils\DateTime;
use app\utils\MatchUtils;
use think\facade\Log;

class BlackService
{

    /**
     * @var SystemConfig[]|array|\think\Collection
     */
    private $system_config;
    /**
     * @var Airports
     */
    private $airports;
    /**
     * @var Airlines
     */
    private $airlines;
    /**
     * @var CharacterUtils
     */
    private $characterUtils;
    /**
     * @var mixed
     */
    private $blackIdArr;
    /**
     * @var TicketService
     */
    private $ticketService;
    /**
     * @var OrderService
     */
    private $orderService;

    public function __construct($identification)
    {
        $this->blackIdArr = $identification['data'];
        $this->airports = new Airports();
        $this->airlines = new Airlines();
        $this->characterUtils = new CharacterUtils();
        $this->ticketService = new TicketService();
        $this->orderService = new OrderService();
        foreach ((new SystemConfig())->select() as $value) {
            $this->system_config[$value->code] = $value->param;
        }

    }

//    OSI 航司 CTCT              固定


    private $phone = [
        "15384344034",//CTCT固定
        "18023096144",//ctcm随机
        "13727034427",
        "18125068053",
        "18023095871",
        "15384344034",
        "13326634215",
        "13377568694",
        "13326624953",
        "13392951846",];

    private $workArr = [
        'ZUH140' => [
            "LT","Y8", "GX", "GS", "9H", "FU", "JD", "HU", "CN", "KN", "KY", "QW", "NS", "RY", "3U", "FM", "MU", "SC", "CZ", "MF", "HO", "ZH", "GJ", "A6", "DZ", "JR"
        ],
        'ZUH118' => [
            "EU", "CA", "MF", "RY", "NS", "HO", "DZ", "ZH", "CZ", "SC", "G5", "JR"
        ],
        'MFM327' => [
            "MU", "CA", "ZH", "BR", "HO", "NX", "JX"
        ]
    ];

    private $papersType = [
        'FOID' => [
            'NI'
        ],
        'DOCS' => [
            'P' => '护照',
            'IP' => '电子护照',
            'M' => '军方证件',
            'G' => '商船船员证',
            'A/C/I' => '身份证件[各国或地区颁发]',
            'F' => '非标证件[名国或地区颁发]',
            'IN 芳邻卡' => '美加'
        ]
    ];


    public function getWorkNo($airlines)
    {
        if (empty($airlines)) return null;

        foreach ($this->workArr as $workNo => $airlinesList) {
            if (in_array($airlines, $airlinesList)) return $workNo;
        }
        throw new ParamException($airlines . '航司未授权');
    }

    public function ff($fly_day, $flight_no)
    {
        $cmd = "FF:" . $flight_no . '/' . date('dM', $fly_day);
        preg_match('/\w\w/', $flight_no,$airlines);
        $airlines = $airlines[0];
        $FFResult = $this->curlPost($cmd, $this->getWorkNo($airlines));

        if (!preg_match('/(\w{3})\s+\d{4}\s+\d{4}.+?&#x000D;/', $FFResult, $airport)) {
            throw new ParamException('不是经停航班啊，别乱查,也可能是我没查对，人工查一下吧');
        }


        $airport = $this->airports->where('code', $airport[1])->find()->name ?? $airport[1];
        return $this->characterUtils->c2t("(经停：{$airport})");


    }


    public function AVHO($time, $voyage, $fly_time = null, $airline = null)
    {

        $cmd = 'AVHO/' . $voyage . '/' . date('dM', $time);
        if (!empty($fly_time)) {
            $cmd .= '/' . $fly_time . '00';
        }
        if (!empty($airline)) {
            $cmd .= '/' . $airline;
            $company = $this->getWorkNo($airline);
        }

        empty($company) && $company = 'ZUH140';
        $cmd .= '/D';
        $AVHOResult = $this->curlPost($cmd, $company);

        if (preg_match('/(\d{2}\w{3})\(\w{3}\)/', $AVHOResult, $timeArr)) {
            $time = strtotime($timeArr[1]);
        }

//        //翻页操作
//        while (true){
//            $PNResult = $this->curlPost('PN', $company);
//            if (preg_match('/'.date('dM', $time).'/', $PNResult)){
//                $AVHOResult.=$PNResult;
//            }else{
//                break;
//            }
//        }


        $result = [];

        if (preg_match_all('/(\d)[\+|\-|\s]\s+(\w{2}\d{2,4})(.+?)(\w{6})\s(\d{4})\s+(\d{4})(.+?)&#x000D/', $AVHOResult, $flightList)) {

            foreach ($flightList[3] as $key => $flightSeat) {


                //如果第一行没有仓那就是没配置
                if (!preg_match_all('/([A-Z])([\d|L|A|Q|S])[^#]/', $flightSeat, $seatArr)) {
                    $result[] = [
                        'stopover' => '',
                        'origin_terminal' => '',
                        'destination_terminal' => '',
                        'no' => $flightList[1][$key],
                        'flight' => $flightList[2][$key],
                        'voyage' => $flightList[4][$key],
                        'fly_day' => $time,
                        'fly_time' => $flightList[5][$key],
                        'down_time' => $flightList[6][$key],
                        'seat' => null,
                        'seatList' => [],
                        'remark' => '无授权该航司'
                    ];
                    continue;
                }

                preg_match('/\w+\s+(\d)\^*.*?\s{3}\s+(.*\s)\s+([T|-]*.*)/', $flightList[7][$key], $seatAndTerminal);
                $origin_terminal = '';
                $destination_terminal = '';

                //噶航站楼
                if (preg_match('/([T|-][\d|-])\s([T|-][\d|-])/', $seatAndTerminal[3], $terminalArr)) {
                    $origin_terminal = $terminalArr[1] == '--' ? '' : $terminalArr[1];
                    $destination_terminal = $terminalArr[2] == '--' ? '' : $terminalArr[2];
                }


                $seatList = $this->setSeat($seatArr);


                preg_match_all('/([A-Z])([\d|L|A|Q|S])[^#]/', $seatAndTerminal[2], $seatArr);

                $seatList = array_merge($seatList, $this->setSeat($seatArr));


                preg_match('/\w\w/', $flightList[2][$key], $airlines);

                $airlinesInfo = $this->airlines->where('airlines', $airlines[0])->find();

                preg_match('/(\w{3})(\w{3})/', $flightList[4][$key], $voyageArr);

                $origin = $this->airports->where('code', $voyageArr[1])->find();
                $destination = $this->airports->where('code', $voyageArr[2])->find();
                //澳門航空NX921 4月10日 吉隆坡KUL-澳門MFM 1840起飛 2240到達
                //特价经济舱：HKD1580/位
                $remark = ($airlinesInfo->airlines_name ?? 'XX航司') . $flightList[2][$key] . date(' m月d日 ', $time);
                $remark .= ($origin->name ?? '') . $origin_terminal . $voyageArr[1] . '-' . ($destination->name ?? '') . $destination_terminal . $voyageArr[2] . ' ';
                $remark .= $flightList[5][$key] . '起飞 ' . $flightList[6][$key] . '到达';
                $result[] = [
                    'stopover' => $seatAndTerminal[1],
                    'origin_terminal' => $origin_terminal,
                    'destination_terminal' => $destination_terminal,
                    'no' => $flightList[1][$key],
                    'flight' => $flightList[2][$key],
                    'voyage' => $flightList[4][$key],
                    'fly_day' => $time,
                    'fly_time' => $flightList[5][$key],
                    'down_time' => $flightList[6][$key],
                    'seat' => json_encode($seatList),
                    'seatList' => $seatList,
                    'remark' => $this->characterUtils->c2t($remark)
                ];

            }
            return ['cmd' => $cmd, 'work_no' => $company, 'flight' => (new FlightAvho())->saveAll($result)];
        }
        return null;
    }

    private function setSeat(array $seatArr)
    {
        $result = [];
        foreach ($seatArr[1] as $key => $seat) {
            $result[$seat] = $seatArr[2][$key];
        }
        return $result;
    }


    public function queryFlightSeatPrice($time, $fly_time, $voyage, $flightNo, array $seatList, $company = null)
    {

        $result = [];
        $peopleNumber = 0;

        preg_match('/\w\w/', $flightNo,$airlines);
        $airlines = $airlines[0];
        if (empty($company)) $company = $this->getWorkNo($airlines);
        foreach ($seatList as $seat) {

            $AVHOCmd = 'AVHO/' . $voyage . '/' . date('dM', $time) . '/' . $fly_time . '/' . $airlines . '/D';
            $AVHOResult = $this->curlPost($AVHOCmd, $company);

            if (preg_match('/(\d)[\+|\-|\s]\s+' . $flightNo . '.*?' . $seat . '([\d|L|A|Q|S])[^#]/', $AVHOResult, $no)) {
                $peopleNumber = $no[2];
                $no = $no[1];

            } else {
                $this->curlPost('I', $company);
                throw new ParamException('获取航班错误，请重试');
            }

//        SD1仓位/GK1
            $SDCmd = 'SD' . $no . $seat . '/GK1';
            $SDResult = $this->curlPost($SDCmd, $company);


            if (!preg_match('/' . $flightNo . '/', $SDResult)) {
                return $SDResult;
            }
            $PATResult = $this->curlPost('PAT:A', $company);

            preg_match_all('/TOTAL:\s*([\d|\s|.]+).*?(SFC:[0-1][1-9])/', $PATResult, $priceList);

            foreach ($priceList[1] as $key => $price) {
                $price = preg_replace('/\s/', '', $price);
                $result[$seat][] = [
                    'HKD' => MatchUtils::ceilToTen((float)$price * $this->system_config['CNY2HKD']),
                    'CNY' => $price,
                    'no' => $priceList[2][$key],
                    'number' => $peopleNumber
                ];
            }
            $this->curlPost('I', $company);
        }

        return $result;
    }

    public function I($company = "ZUH140")
    {
        $this->curlPost('I', $company);
    }


//CODAPI140   epe3pjl38x8s
//CODAPI118  epe3pjl38x8s
//CODAPI327   epe3pjl38x8s

    public function curlPost($cmd, $company = "ZUH140")
    {

        if (empty($this->blackIdArr[$company])) throw new ServiceException('黑屏配置错误');
        $postUrl = 'http://8.134.128.125:18119/GetData/soap/get.do';
        $post_data = "cmd=" . urlencode($cmd);
        $post_data .= "&user={$this->blackIdArr[$company]['user']}&pwd={$this->blackIdArr[$company]['pwd']}";//重点
        $ch = curl_init(); // 初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); // 抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 1); // 设置header
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $data = curl_exec($ch); // 运行curl
        curl_close($ch);
        preg_match('/RESULT([\S\s]+)\/RESULT/', $data, $result);
        $result = html_entity_decode($result[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
        Log::channel('black')->info("黑屏记录>{$company}>cmd: {$cmd}>>>>" . $result);

        return $result;
    }

    public function queryCHDSeatPrice($time, $fly_time, $voyage, $flightNo, $seat, $is_chd_price = true, $company = null)
    {

        $result = [];
        $peopleNumber = 0;
        preg_match('/\w\w/', $flightNo,$airlines);
        $airlines = $airlines[0];
        if (empty($company)) $company = $this->getWorkNo($airlines);
        $this->curlPost('I', $company);
        $AVHOCmd = 'AVHO/' . $voyage . '/' . date('dM', $time) . '/' . $fly_time . '/' . $airlines . '/D';
        $AVHOResult = $this->curlPost($AVHOCmd, $company);

        if (preg_match('/(\d)[\+|\-|\s]\s+' . $flightNo . '.*?' . $seat . '([\d|L|A|Q|S])/', $AVHOResult, $no)) {
            $peopleNumber = $no[2];
            $no = $no[1];

        } else {
            $this->curlPost('I', $company);
            throw new ParamException('获取航班错误，请重试');
        }

//        SD1仓位/GK1
        $SDCmd = 'SD' . $no . $seat . '/GK1';
        $SDResult = $this->curlPost($SDCmd, $company);


        if (!preg_match('/' . $flightNo . '/', $SDResult)) {
            return $SDResult;
        }
        $PATResult = $this->curlPost('PAT:A', $company);

        preg_match_all('/FARE:CNY\s*([\d|\s|.]+).+?TOTAL:\s*([\d|\s|.]+).*?(SFC:[0-1][1-9])/', $PATResult, $priceList);

        foreach ($priceList[1] as $key => $price) {
            if ($is_chd_price) $price = (float)$price * 0.5;
            $price += $this->system_config['CHDSF'];
            $result[] = [
                'HKD' => MatchUtils::ceilToTen($price * $this->system_config['CNY2HKD']),
                'CNY' => $price,
                'no' => $priceList[3][$key],
                'number' => $peopleNumber
            ];
        }
        $this->curlPost('I', $company);

        return $result;
    }

    public function queryINFTSeatPrice($time, $fly_time, $voyage, $flightNo, $seat, $company = null)
    {

        $result = [];
        $peopleNumber = 0;
        preg_match('/\w\w/', $flightNo,$airlines);
        $airlines = $airlines[0];
        if (empty($company)) $company = $this->getWorkNo($airlines);
        $this->curlPost('I', $company);
        $AVHOCmd = 'AVHO/' . $voyage . '/' . date('dM', $time) . '/' . $fly_time . '/' . $airlines . '/D';
        $AVHOResult = $this->curlPost($AVHOCmd, $company);

        if (preg_match('/(\d)[\+|\-|\s]\s+' . $flightNo . '.*?' . $seat . '([\d|L|A|Q|S])/', $AVHOResult, $no)) {
            $peopleNumber = $no[2];
            $no = $no[1];

        } else {
            $this->curlPost('I', $company);
            throw new ParamException('获取航班错误，请重试');
        }

//        SD1仓位/GK1
        $SDCmd = 'SD' . $no . $seat . '/GK1';
        $SDResult = $this->curlPost($SDCmd, $company);


        if (!preg_match('/' . $flightNo . '/', $SDResult)) {
            return $SDResult;
        }
        $PATResult = $this->curlPost('PAT:A', $company);

        preg_match_all('/FARE:CNY\s*([\d|\s|.]+).+?TOTAL:\s*([\d|\s|.]+).*?(SFC:[0-1][1-9])/', $PATResult, $priceList);

        foreach ($priceList[1] as $key => $price) {
            $price = (float)$price * 0.1;
            $result[] = [
                'HKD' => MatchUtils::ceilToTen($price * $this->system_config['CNY2HKD']),
                'CNY' => $price,
                'no' => $priceList[3][$key],
                'number' => $peopleNumber
            ];
        }
        $this->curlPost('I', $company);

        return $result;
    }

    public function booking($orderInfo, $passengerList, $ticketList, $out_who, $adu_big_pnr = '')
    {
        $result = [
            'adu_pnr' => null,
            'chd_pnr' => null,
        ];
        $stop = 0;
        $company = $orderInfo['office_no'];
        preg_match('/\w\w/', $orderInfo['flight_no'],$airlines);
        $airlines = $airlines[0];
        $fly_time = preg_replace('/:\d\d/', '', $orderInfo['fly_time']);

        $fly_day = date('dM', $orderInfo['format_fly_day']);

        //如果出成人才出成人
        if ($out_who == 'adu') {
            if (count($passengerList['adu']) < 1) {
                throw new ParamException('怎么没成人信息的');
            }

            $result['adu_pnr'] = $this->_booking($company, $orderInfo, $passengerList['adu'], $passengerList['inft'], $ticketList, $fly_time, $fly_day, $airlines);
            //如果大人定失败直接结束
            if ($result['adu_pnr']['pnr'] == null) {
                return $result;
            }

            $this->ticketService->loadPnr($orderInfo['id'], array_map(function ($passenger) {
                return $passenger['id'];
            }, $passengerList['adu']), $result['adu_pnr']['pnr'], $result['adu_pnr']['big_pnr']);

            if ($result['adu_pnr']['big_pnr'] == null)$stop = 1;

            $adu_big_pnr = $result['adu_pnr']['big_pnr'];
        }
        $order_status = 8;
        if ($stop != 1){
            if (count($passengerList['chd'])>0){
                $result['chd_pnr'] = $this->_booking($company,$orderInfo, $passengerList['chd'],[],$ticketList, $fly_time, $fly_day, $airlines, true, $adu_big_pnr);
                //如果小孩定失败就返回大人信息，订单半定位
                if ($result['chd_pnr']['pnr'] != null) {
                    $order_status = 1;
                }
            }
        }



        $this->orderService->updateStart($orderInfo['id'], $order_status);
        return $result;
    }


    private function discard_bookingAdu($company, $orderInfo, $aduList, $inftList, $ticketList, $fly_time, $fly_day, $airline)
    {
        $result = [
            'pnr' => null,
            'big_pnr' => null,
            'cmd' => null,
            'error' => null,
            'info' => null,
        ];
        $pNo = 1;
        $seat = $ticketList[$aduList[0]['name']]['seat'];
        $result = $this->AVHOAfterSS($result, $orderInfo, $fly_day, $fly_time, $airline, $company, $aduList, $seat);
        if (!empty($result['error'])) return $result;


        $result['cmd']['NM'] = 'NM';
        foreach ($aduList as $passenger) {
            $result['cmd']['NM'] .= '1' . $passenger['name'];
        }
        $NMResult = $this->curlPost($result['cmd']['NM'], $company);

        if (!preg_match('/' . $orderInfo['flight_no'] . '/', $NMResult)) {
            $this->curlPost('I', $company);
            $result['error'] .= 'NM错误';
            $result['info'] = $NMResult;
            return $result;
        }

        $result['cmd']['TKTL'] = 'TKTL' . ($fly_time - 2) . '00/' . $fly_day . '/' . $company;
        $this->curlPost($result['cmd']['TKTL'], $company);

        $OSICT = 'OSI ' . $airline;

        $result['cmd']['OSICT'] = $OSICT . ' CTCT' . $this->phone[0];
        $OSICTCTResult = $this->curlPost($result['cmd']['OSICT'], $company);
        if (!preg_match('/' . $this->phone[0] . '/', $OSICTCTResult)) {
            $this->curlPost('I', $company);
            $result['error'] .= 'OSI CTCT错误';
            $result['info'] = $OSICTCTResult;
            return $result;
        }

        $phoneArr = $this->phone;
        foreach ($aduList as $key => $passenger) {
            $phone = $phoneArr[$key];
            unset($phoneArr[$key]);
            $OSICTCMCmd = $OSICT . ' CTCM' . $phone . '/p' . $pNo;
            $result['cmd']['OSICTCM'] = ($result['cmd']['OSICTCM'] ?? ' ') . "\n" . $OSICTCMCmd;
            $OSICTCMResult = $this->curlPost($OSICTCMCmd, $company);
            if (!preg_match('/' . $phone . '/', $OSICTCMResult)) {
                $this->curlPost('I', $company);
                $result['error'] .= 'OSI CTCM错误';
                $result['info'] = $OSICTCMResult;
                return $result;
            }


            //看证件
            $SSRCmd = '';
            if ($passenger['card_type'] == 'NI') {
                $SSRCmd = "SSR FOID " . $airline . ' HK/NI' . $passenger['id_card'] . '/p' . $pNo;
                $result['cmd']['SSR FOID'] = ($result['cmd']['SSR FOID'] ?? ' ') . "\n" . $SSRCmd;
            } else {
                $SSRCmd = 'SSR DOCS ' . $airline . ' HK1 ' . $passenger['card_type'] . '/' . $passenger['nationality'] . '/' . $passenger['id_card'] . '/' . $passenger['nationality'] . '/' . DateTime::d2m($passenger['birthday']) . '/' . ($passenger['sex'] == 1 ? 'M' : 'F') . '/' . DateTime::d2m($passenger['card_expiration']) . '/' . preg_replace('/,\s*/', '/', strtoupper($passenger['second_name'])) . '/p' . $pNo;
                $result['cmd']['SSR DOCS'] = ($result['cmd']['SSR DOCS'] ?? ' ') . "\n" . $SSRCmd;
            }

            $SSRResult = $this->curlPost($SSRCmd, $company);
            if (!preg_match('/' . $passenger['id_card'] . '/', $SSRResult)) {
                $this->curlPost('I', $company);
                $result['error'] .= 'SSR错误';
                $result['info'] = $SSRResult;
                return $result;
            }

            //有婴儿
            if (array_key_exists($passenger['name'], $inftList)) {
                $inft = $inftList[$passenger['name']];
                $inftNameArr = explode('@', $inft['name']);
                if (empty($inftNameArr[1]) || !preg_match('/\//', $inftNameArr[1])) {
                    $result['error'] .= '婴儿名错误所以没有将婴儿加入到编码中，格式（中文名@姓/名';
                }

                //XN:IN/黄桂红 INF(oct23)/P1
                $XNINCmd = "XN:IN/" . $inftNameArr[0] . ' INF(' . date('My', strtotime($inft['birthday'])) . ')/P' . $pNo;
                $result['cmd']['XNIN'] = ($result['cmd']['XNIN'] ?? ' ') . "\n" . $XNINCmd;
                $XNINResult = $this->curlPost($XNINCmd, $company);
                if (!preg_match('/XN\/IN/', $XNINResult)) {
                    $this->curlPost('I', $company);
                    $result['error'] .= 'XNIN错误';
                    $result['info'] = $XNINResult;
                    return $result;
                }

                //SSR INFT SC NN1 CANTAO SC4676 H 27APR HUANG/GUIHONG 01OCT23/p1
                $SSRINFTCmd = "SSR INFT " . $airline . ' NN1 ' . $orderInfo['voyage'] . ' ' . $orderInfo['flight_no'] . ' ' . $seat . date('dM', strtotime($fly_day)) . ' ' . $inftNameArr[1] . ' ' . date('dMy', strtotime($inft['birthday'])) . '/P' . $pNo;
                $result['cmd']['SSRINFT'] = ($result['cmd']['SSRINFT'] ?? ' ') . "\n" . $SSRINFTCmd;
                $SSRINFTResult = $this->curlPost($SSRINFTCmd, $company);
                if (!preg_match('/SSR INFT/', $SSRINFTResult)) {
                    $this->curlPost('I', $company);
                    $result['error'] .= 'SSR INFT错误';
                    $result['info'] = $SSRINFTResult;
                    return $result;
                }
            }


            $pNo++;
        }

        return $this->KI($result, $company);
    }

    private function insert_cmd($old_cmd, $add){
        return $old_cmd."\n ".$add;
    }

    //$company, $orderInfo, $chdList, $ticketList, $fly_time, $fly_day, $airline, $adu_big_pnr
    private function _booking($company, $orderInfo, $passengerList, $inftList, $ticketList, $fly_time, $fly_day, $airline, $is_chd = false, $adu_big_pnr = '')
    {
        $result = [
            'pnr' => null,
            'big_pnr' => null,
            'cmd' => null,
            'error' => null,
            'info' => null,
        ];
        $pNo = 1;
        $seat = $ticketList[$passengerList[0]['name']]['seat'];

        //        ss SC1160 H 01MAY zuhpek 3
        $result['cmd'] = $this->insert_cmd($result['cmd'],  'SS ' . $orderInfo['flight_no'] . ' ' . $seat . ' ' . $fly_day . ' ' . $orderInfo['voyage'] . ' ' . count($passengerList));

        $NMCmd = 'NM';
        foreach ($passengerList as $passenger) {
            if ($is_chd){
                $NMCmd .= '1' . $passenger['name'] .'CHD';
            }else{
                $NMCmd .= '1' . $passenger['name'];
            }
        }
        $result['cmd'] = $this->insert_cmd($result['cmd'], $NMCmd);
        $result['cmd'] = $this->insert_cmd($result['cmd'], 'TKTL' . ($fly_time - 2) . '00/' . $fly_day . '/' . $company);

        $OSICT = 'OSI ' . $airline;
        $result['cmd'] = $this->insert_cmd($result['cmd'], $OSICT . ' CTCT' . $this->phone[0]);

        $phoneArr = $this->phone;
        foreach ($passengerList as $key => $passenger) {
            $phone = $phoneArr[$key+1];
            $result['cmd'] = $this->insert_cmd($result['cmd'], $OSICT . ' CTCM' . $phone . '/p' . $pNo);


            //看证件
            if ($passenger['card_type'] == 'NI') {
                $SSRCmd = "SSR FOID " . $airline . ' HK/NI' . $passenger['id_card'] . '/p' . $pNo;
            } else {
                $SSRCmd = 'SSR DOCS ' . $airline . ' HK1 ' . $passenger['card_type'] . '/' . $passenger['nationality'] . '/' . $passenger['id_card'] . '/' . $passenger['nationality'] . '/' . DateTime::d2m($passenger['birthday']) . '/' . ($passenger['sex'] == 1 ? 'M' : 'F') . '/' . DateTime::d2m($passenger['card_expiration']) . '/' . preg_replace('/,/', '/', strtoupper($passenger['second_name'])) . '/p' . $pNo;
            }
            $result['cmd'] = $this->insert_cmd($result['cmd'], $SSRCmd);

            //有婴儿
            if (array_key_exists($passenger['name'], $inftList)) {
                $inft = $inftList[$passenger['name']];
                $inftNameArr = explode('@', $inft['name']);
                if (empty($inftNameArr[1]) || !preg_match('/\//', $inftNameArr[1])) {
                    $result['error'] .= '婴儿名错误所以没有将婴儿加入到编码中，格式（中文名@姓/名';
                }

                //XN:IN/黄桂红 INF(oct23)/P1
                $XNINCmd = "XN:IN/" . $inftNameArr[0] . ' INF(' . date('My', strtotime($inft['birthday'])) . ')/P' . $pNo;
                $result['cmd'] = $this->insert_cmd($result['cmd'], $XNINCmd);

                //SSR INFT SC NN1 CANTAO SC4676 H 27APR HUANG/GUIHONG 01OCT23/p1
                $SSRINFTCmd = "SSR INFT " . $airline . ' NN1 ' . $orderInfo['voyage'] . ' ' . $orderInfo['flight_no'] . ' ' . $seat . date('dM', strtotime($fly_day)) . ' ' . $inftNameArr[1] . ' ' . date('dMy', strtotime($inft['birthday'])) . '/P' . $pNo;
                $result['cmd'] = $this->insert_cmd($result['cmd'], $SSRINFTCmd);
            }
            $pNo++;
        }

        if ($is_chd){
            $result['cmd'] = $this->insert_cmd($result['cmd'], "OSI ".$airline." PAX WZ ".$adu_big_pnr);
        }


        return $this->KI($result, $company);
    }

    private function getBigPnr($result, $pnr, $company){
        $RTResult = $this->curlPost('RT' . $pnr, $company);

        if (preg_match('/RMK\sCA\/(\w{6})/', $RTResult, $big_pnr)){
            $result['big_pnr'] = $big_pnr[1];
        }else{
            $result['error'] .= 'BIGPNRGETERROR|获取大PNR失败,如果有定儿童请人工填写大PNR后继续定位';
            $result['info'] = $RTResult;

        }
        return $result;
    }




    private function KI($result, $company)
    {
        $result['cmd'] = $this->insert_cmd($result['cmd'], '\KI');
        $KIResult = $this->curlPost($result['cmd'], $company);


        if (preg_match('/INVALID CHARACTER ERROR/', $KIResult, $pnr)) {
            $result['error'] .= '最后强封错误,请检查乘机人信息，特别是国籍以及发证国家是否定义为二字代码';
            $result['info'] = $KIResult;
        } else if (preg_match('/DUPLICATE TEL NUMBER/', $KIResult, $pnr)) {
            $result['error'] .= '最后强封错误,电话号码随机没到位，重复了';
            $result['info'] = $KIResult;

        } else if (preg_match('/(\w{6})\s\-EOT\sSUCCESSFUL/', $KIResult, $pnr)) {
            $result['pnr'] = $pnr[1];
            $result = $this->getBigPnr($result, $pnr[1],$company);

        } else {

            $result['error'] .= '最后强封错误';
            $result['info'] = $KIResult;

        }
        $this->curlPost('I', $company);
        return $result;
    }





}